package com.kwok.rbac.application.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kwok.rbac.application.entity.SystemUser;
import com.kwok.rbac.application.entity.SystemUserToken;
import com.kwok.rbac.application.exception.PasswordErrorException;
import com.kwok.rbac.application.exception.SystemUserIsNullException;
import com.kwok.rbac.application.mapper.SystemUserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kwok.rbac.application.service.SystemUserService;
import com.kwok.rbac.application.service.TokenService;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2024-05-25
 */
@Service
public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper, SystemUser> implements SystemUserService {

    @Autowired
    private TokenService tokenService;

    @Override
    public SystemUserToken login(String username, String password) {
        //通过用户名查询系统用户
        SystemUser systemUser = getUserByUsername(username);
        //判断用户是否存在数据库
        if (systemUser == null){
            throw new SystemUserIsNullException(2001,"用户不存在");
        }
        //判断密码是否正确(第一个参数为用户输入的的明文密码，第二个参数为数据库中的加密密码)
        if (!BCrypt.checkpw(password, systemUser.getPassword())){
            throw new PasswordErrorException(2002,"密码错误");
        }
        //登录认证完成，响应一个token给客户端用户
        SystemUserToken systemUserToken = tokenService.createToken(systemUser);
        //返回token
        return systemUserToken;
    }

    //通过用户名查询系统用户
    @Override
    public SystemUser getUserByUsername(String username) {
        QueryWrapper<SystemUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return baseMapper.selectOne(queryWrapper);
    }

}
